<script lang="ts">
  import { Modal } from "@skeletonlabs/skeleton-svelte";
  import { X } from "lucide-svelte";
  import { getContext } from "svelte";
  import type { Store as ToastStore } from "@zag-js/toast";
  import { request } from "$lib/utils/request";
  import { change_passwd } from "$lib/api/user";
  import { userStore } from "$lib/stores/user.svelte";

  const toast: ToastStore = getContext("toast");

  interface ModalProps {
    onClose: () => void;
  }

  let props: ModalProps = $props();

  let oldPasswd = $state("");
  let newPasswd = $state("");

  async function changePasswd() {
    if (oldPasswd == "" || newPasswd == "") {
      return;
    }
    if (oldPasswd == newPasswd) {
      toast.create({
        title: "警告",
        description: "新旧密码不能相同!",
        type: "error",
      });
      return;
    }
    await request(
      change_passwd({
        session_id: userStore.userSession,
        old_passwd: oldPasswd,
        new_passwd: newPasswd,
      })
    );
    toast.create({
      title: "成功",
      description: "修改密码成功!",
      type: "success",
    });
    props.onClose();
  }
</script>

<Modal
  open={true}
  triggerBase="btn preset-tonal"
  contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl w-[500px]"
  backdropClasses="backdrop-blur-xs"
  backdropBase="backdrop-none"
  onOpenChange={(ev) => {
    if (!ev.open) {
      props.onClose();
    }
  }}
>
  {#snippet content()}
    <header class="flex justify-between">
      <h4 class="h4">修改密码</h4>
      <button
        type="button"
        class="btn preset-ghost-primary-500"
        onclick={() => props.onClose()}
      >
        <X />
      </button>
    </header>

    <label class="label">
      <span class="label-text">当前密码</span>
      <input
        class="input bg-surface-50-950 rounded-none"
        type="password"
        bind:value={oldPasswd}
        placeholder="请输入当前密码"
      />
    </label>
    <label class="label">
      <span class="label-text">新密码</span>
      <input
        class="input bg-surface-50-950 rounded-none"
        type="password"
        bind:value={newPasswd}
        placeholder="请输入新密码"
      />
    </label>

    <footer class="flex justify-end gap-4 mt-[20px]">
      <button
        type="button"
        class="btn preset-tonal"
        onclick={() => props.onClose()}>取消</button
      >
      <button
        type="button"
        class="btn preset-filled-primary-900-100"
        disabled={oldPasswd == "" || newPasswd == ""}
        onclick={() => {
          changePasswd();
        }}
      >
        修改
      </button>
    </footer>
  {/snippet}
</Modal>
